package com.lwl.nio.net;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by liwenlong on 2017/11/28 19:39
 */
public class ConnectAsync {

    public static void main(String[] args) throws IOException {
        String host = "127.0.0.1";
        int port = 1234;
        InetSocketAddress address = new InetSocketAddress(host, port);
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        System.out.println("initiating connection");
        socketChannel.connect(address);
        while (!socketChannel.finishConnect()){
            doSomethingUseful( );
        }
        System.out.println("connection established");
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        socketChannel.read(allocate);
        allocate.flip();
        String s = new String(allocate.array());
        System.out.println(s);

        socketChannel.close();
    }

    private static void doSomethingUseful() {
        System.out.println("doing someting useless");
    }


}
